package com.feng.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限会去往登录页面，以及login页面表单提交验证请求
        //usernameParameter("name")设置login页面中的表单中的每一个参数的name的值。
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login").usernameParameter("name").passwordParameter("password");

        //注销
        http.logout().logoutSuccessUrl("/");

        //关闭csrf,防止被跨域攻击
        http.csrf().disable();

        //开启记住我功能
        //自定义记住我
        http.rememberMe().rememberMeParameter("remember");
    }

    /**
     * //认证
     * java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user1").password(new BCryptPasswordEncoder().encode("user1")).roles("vip1")
                .and()
                .withUser("user2").password(new BCryptPasswordEncoder().encode("user2")).roles("vip2")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1","vip2","vip3");
    }
}
